package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm calculateDrivingLineForm) {

        // 要访问的腾讯的定位服务接口地址
        //模板：https://apis.map.qq.com/ws/direction/v1/driving/
        // ?from=39.915285,116.403857
        // &to=39.915285,116.803857
        // &key=[你的key]
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from=" +
                "{from}&to={to}&key={key}";

        // 起始经纬度
        String begin = calculateDrivingLineForm.getStartPointLongitude() + "," +
                calculateDrivingLineForm.getStartPointLatitude();
        url.replace("{from}", begin);

        // 结束经纬度
        String end = calculateDrivingLineForm.getEndPointLongitude() + "," +
                calculateDrivingLineForm.getEndPointLatitude();
        url.replace("{to}", end);

        // 使用restTemplate实现远程调用
        JSONObject result = restTemplate.getForObject(url, JSONObject.class);

        //处理返回结果
        //判断调用是否成功
        int status = result.getIntValue("status");
        if(status != 0) {//失败
            throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }

        //获取返回路线信息
        JSONObject route =
                result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);

        //创建vo对象
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        //预估时间
        drivingLineVo.setDuration(route.getBigDecimal("duration"));
        //距离  6.583 == 6.58 / 6.59
        drivingLineVo.setDistance(route.getBigDecimal("distance")
                .divide(new BigDecimal(1000))
                .setScale(2, RoundingMode.HALF_UP));
        //路线
        drivingLineVo.setPolyline(route.getJSONArray("polyline"));

        return drivingLineVo;
    }
}
